'use strict'

const {SqliteStorage} = require('ee-core/storage')
const {getDataDir} = require('ee-core/ps')
const path = require('node:path')

/**
 * Sqlite
 */
class DbConnectionService {
    conn = null

    constructor(options) {
        const {dbname} = options
        this.dbname = dbname
    }

    /*
     * 初始化
     */
    _init() {
        const dbFile = path.join(getDataDir(), 'db', this.dbname)
        const sqliteOptions = {
            timeout: 6000,
            verbose: console.log
        }
        this.storage = new SqliteStorage(dbFile, sqliteOptions)
        this.conn = this.storage.db
    }

    /*
     * change data dir (sqlite)
     */
    changeDataDir(dir) {
        // the absolute path of the db file
        const dbFile = path.join(dir, this.dbname)
        const sqliteOptions = {
            timeout: 6000,
            verbose: console.log
        }
        this.storage = new SqliteStorage(dbFile, sqliteOptions)
        this.conn = this.storage.db
    }
}

DbConnectionService.toString = () => '[class DbConnectionService]'
module.exports = {
    DbConnectionService
}